<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\http\HttpRequest;

/**
 * 管理员登录日志 action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class ManagerLoginLogAction extends CommonAction {

    protected $serviceBean = 'admin.loginLog.service';
    protected $actionTitle = '管理员登录日志';

    //数据列表页面
    public function index( HttpRequest $request ) {

        $username = $request->getParameter('username', 'trim');
        $ip = $request->getParameter('ip', 'trim');
        $starttime = $request->getParameter('starttime', 'trim');
        $endtime = $request->getParameter('endtime', 'trim');

        $conditions = array();
        if ( $username ) $conditions['username'] = "%{$username}%";
        if ( $ip ) $conditions['ip'] = $ip;
        if ( $starttime ) $conditions['addtime']['>='] = $starttime.' 00:00:00';
        if ( $endtime ) $conditions['addtime']['<='] = $endtime.' 24:00:00';

        $this->setConditions($conditions);
        $this->setOrder(array('id' => -1));
        $this->assign('tableHeader', array('用户名','姓名','登录时间','登录IP'));
        if ( $request->getParameter('__export') == 1 ) {

            $this->export($request); //导出数据
        } else {

            parent::index($request);
            $this->setView('log/login_log');
            $this->assign('breadcrumb', array('日志管理', '登录日志'));
        }
    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this -> setConditions($conditions);
            }
            $this->setPagesize(getConfig('export_max_count'));
            $service = Beans::get($this->getServiceBean());
            $items = $service->where($this->getConditions())->limit(1, $this->getPagesize())->sort(array('addtime' => -1))->find();
            $excel = array();
            foreach($items as $k => $v)
            {
                $tmp = array();
                $tmp[] = $v["username"];
                $tmp[] = $v["name"];
                $tmp[] = $v["addtime"];
                $tmp[] = $v["ip"];
                $excel[] = $tmp;
            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel("管理员登录日志",$header,$excel);
            exit();
        }
    }
}
